package com.alinakipoglu.asprocedural
{
	import com.alinakipoglu.asprocedural.interfaces.IPorceduralContext;
	import com.alinakipoglu.asprocedural.interfaces.IProceduralContextUpdater;
	import com.alinakipoglu.asprocedural.interfaces.IProcedure;
	
	public class DefaultContextUpdater implements IProceduralContextUpdater
	{
		private var m_validProcedures	:Vector.<IProcedure>;
		
		public function DefaultContextUpdater()
		{
			m_validProcedures		= new Vector.<IProcedure>();
		}
		
		public function update(_value:IPorceduralContext):void
		{
			var _procedures				:Vector.<IProcedure>	= _value.procedures;
			var _procedureCount			:uint					= _procedures.length;
			var _validProcedureCount	:uint					= 0;
			
			var _procedure				:IProcedure;
			var _procedureToBeExecuted	:IProcedure;
			
			for(var i:uint; i < _procedureCount; i++)
			{
				_procedure	= _procedures[i];
				
				if(_procedure.check(_value))
				{
					m_validProcedures[_validProcedureCount]	= _procedure;
					
					_validProcedureCount++;
				}
			}
			
			if(_validProcedureCount > 0)
			{
				_procedureToBeExecuted	= m_validProcedures[Math.floor(Math.random() * _validProcedureCount)];
				
				_procedureToBeExecuted.execute(_value);
				
				_value.idStack.push(_procedureToBeExecuted.id);
			}
		}
	}
}